package com.longshine.mobile.component.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HostnameVerifier;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.HostNameResolver;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class HttpConnection {

	private static final String encoding = HTTP.UTF_8;
	private static HttpClient httpClient;

	private HttpConnection() {
	}
	/**
	 * 获得httpclient实例
	 * @return
	 */
	public static synchronized HttpClient getHttpClient() {

		if (httpClient == null) {
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, encoding);
			HttpProtocolParams.setUseExpectContinue(params, true);

			HttpProtocolParams
					.setUserAgent(
							params,
							"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
									+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 超时设置
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, 1000 * 5);
			/* 连接超时 */
			HttpConnectionParams.setConnectionTimeout(params, 1000 * 15);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, 1000 * 20);

			// 设置HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory
					.getSocketFactory(), 443));

			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
			httpClient = new DefaultHttpClient(conMgr, params);
		}
		return httpClient;
	}
	public static byte[] httpConnect(HttpRequest request) throws Exception {
		HttpResponse response = null;
		if (request instanceof HttpGet) {
			HttpGet get = (HttpGet) request;

			response = getHttpClient().execute(get);

		} else if (request instanceof HttpPost) {
			HttpPost post = (HttpPost) request;
			response = getHttpClient().execute(post);

		}
		if (response != null
				&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity resEntity = response.getEntity();

			return (resEntity == null) ? null : EntityUtils
					.toByteArray(resEntity);
		}
		return null;
	}
//	private static String tag = "httpUtil Wrong";
	//
//		public static String doGet(Context context, String url) {
//			HttpEntity resEntity = null;
//			HttpHost proxy = null;
//			if (NetStateUtil.getNetState(context) != NetStateUtil.none) {
//				try {
//					HttpGet get = new HttpGet(url);
//					// 如果为移动wap上网，则需要设置代理
//					if (NetStateUtil.getNetState(context).equals(
//							NetStateUtil.mobile_wap)) {
//						proxy = new HttpHost("10.0.0.172", 80);
//						getHttpClient().getParams().setParameter(
//								ConnRoutePNames.DEFAULT_PROXY, proxy);
//					}
//					HttpResponse response = getHttpClient().execute(get);
//					if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//						resEntity = response.getEntity();
//						return (resEntity == null) ? null : EntityUtils.toString(
//								resEntity, encoding);
//					}
//				} catch (Exception e) {
//					Log.e(tag, e.getMessage());
//				}
//			} else {
//				Toast.makeText(context, "无可用网络", Toast.LENGTH_SHORT).show();
//			}
//			return null;
//		}
	//
//		/**
//		 * post请求
//		 * 
//		 * @param url
//		 *            访问路径
//		 * @param params
//		 *            参数集合
//		 * @return 服务器响应
//		 */
//		public static String doPost(Context context, String url,
//				NameValuePair... params) {
//			HttpHost proxy = null;
//			if (NetStateUtil.getNetState(context) != NetStateUtil.none) {
//				try {
//					// 请求参数
//					List formparams = new ArrayList();
//					for (NameValuePair p : params) {
//						formparams.add(p);
//					}
//					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
//							formparams, encoding);
//					// 创建POST请求
//					HttpPost request = new HttpPost(url);
	//
//					request.setEntity(entity);
//					// 如果为移动wap上网，则需要设置代理
//					if (NetStateUtil.getNetState(context).equals(
//							NetStateUtil.mobile_wap)) {
//						proxy = new HttpHost("10.0.0.172", 80);
//						getHttpClient().getParams().setParameter(
//								ConnRoutePNames.DEFAULT_PROXY, proxy);
//					}
//					// 发送请求
//					HttpClient client = getHttpClient();
//					HttpResponse response = client.execute(request);
//					if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//						HttpEntity resEntity = response.getEntity();
	//
//						return (resEntity == null) ? null : EntityUtils.toString(
//								resEntity, encoding);
//					}
	//
//				} catch (Exception e) {
//					Log.e(tag, e.getMessage());
	//
//				}
//			} else {
//				Toast.makeText(context, "无可用网络", Toast.LENGTH_SHORT).show();
//			}
//			return null;
//		}
}
